

window.onload = () => {
    let onlineUsers = []

    // 获取用户名
    let username = getUsername()

    // 设置 websocket
    let socket = setWebSocket(onlineUsers, username)

    // 设置发送按钮点击事件
    setSendBtnOnclick(socket)

    // 设置 textarea 换行键为 ctrl+回车
    setTextAreaKeyEvent()

}

function getUsername() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:8080/getUsername', false); // 第三个参数设置为false表示同步请求
    xhr.send();

    if (xhr.status === 200) {
        let response = xhr.responseText
        let responseJson = JSON.parse(response)
        let username = responseJson.username
        let usernameSpan = document.getElementById("username")
        let fromName = document.getElementById("from-name")
        usernameSpan.innerText = username
        fromName.value = username
        return username
    } else {
        console.error('Request failed. Status code:', xhr.status);
    }

}

function setSendBtnOnclick(socket) {
    let form = document.getElementById("chat-message-form")
    form.addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为
        let formData = new FormData(form)
        if (formData.get("message") === "") {
            alert("发送的消息不能为空")
            return
        }
        const msg = {
            fromName: formData.get("fromName"),
            toName: formData.get("toName"),
            message: formData.get("message")
        }
        let msgJson = JSON.stringify(msg)
        // 将消息发送到服务器
        sendMessage(socket, msgJson)
    })
}

function setFriendListItemOnClick(item) {
    let title = document.getElementById("title")
    let friendName = document.getElementsByClassName("friend-name")
    let body = document.getElementsByClassName("body")
    let toNameInput = document.getElementById("to-name")
    let name = item.innerText
    item.addEventListener("click", () => {
        console.log(item.innerText)
        title.style.display = "block"
        friendName[0].innerText = name
        toNameInput.value = name
        // TODO 查询对应的聊天记录
        body[0].style.display = "block"
    })
}

function setWebSocket(onlineUsers, username) {
    let socket = new WebSocket('ws://localhost:8080/chat');
    let friendList = document.getElementById("friend-list")
    let sysBoCastList = document.getElementById("system-broadcast-list")
    let chatList = document.getElementById("chat-list")
    socket.onopen = function (event) {
        console.log('WebSocket 连接已打开');
    };
    socket.onmessage = function (event) {
        // 接收到消息时更新聊天内容
        let message = event.data;
        let messageJson = JSON.parse(message)
        if (messageJson.cause == null) {
            console.log("message= " + message)
            handleUserMessage(chatList, messageJson.message)
        }
        if (messageJson.cause === "open") {
            handleOpenSystemMessage(messageJson, onlineUsers, username, friendList, sysBoCastList)
        }
        if (messageJson.cause === "close") {

        }
    };
    return socket
}

function sendMessage(socket, msgJson) {
    // 发送消息
    let input = document.getElementById('message');
    socket.send(msgJson);
    /*
        <li>
            <div id="chat-myself">
                <div class="img"></div>
                <div class="bubble">
                    <p>你好，小丽</p>
                </div>
            </div>
        </li>
    */
    // 添加item
    let chatList = document.getElementById("chat-list")
    let newChatItem = document.createElement("li")
    newChatItem.innerHTML = "<div id='chat-myself'><div class='img'></div><div class='bubble'><p>" +
        input.value + "</p></div></div>"
    chatList.appendChild(newChatItem)
    input.value = ''; // 清空输入框
}

function handleUserMessage(chatList, message) {
    /*
        <li>
            <div id="chat-friend">
                <div class="img"></div>
                <div class="bubble">
                    <p>你好，小丽</p>
                </div>
            </div>
        </li>
     */
    let newChatItem = document.createElement("li")
    newChatItem.innerHTML = "<div id='chat-friend'><div class='img'></div><div class='bubble'><p>" +
                            message + "</p></div></div>"
    chatList.appendChild(newChatItem)
}

/*
"<div id='chat-myself'><div class='img'></div><div class='bubble'><p>" +
                            message + "</p></div></div>"
 */

function handleOpenSystemMessage(messageJson, onlineUsers, username, friendList, sysBoCastList) {
    let friends = messageJson.message // array
    friends.forEach((friend) => {
        if (!onlineUsers.includes(friend)) {
            if (friend !== username) {
                createNewFriendItem(friendList, friend)
                createNewSystemBroadcastItem(sysBoCastList, friend)
            }
            onlineUsers.push(friend)
        }
    })
    console.log(onlineUsers)
}

function createNewFriendItem(friendList, friend) {
    let newItem = document.createElement("li")
    newItem.textContent = friend
    setFriendListItemOnClick(newItem)
    friendList.appendChild(newItem)
}

function createNewSystemBroadcastItem(sysBoCastList, friend) {
    // <li>您的好友&nbsp;<span class="friend-name">张三</span>&nbsp;&nbsp;已上线</li>
    let newSysBoCastItem = document.createElement("li")
    newSysBoCastItem.innerHTML = "您的好友&nbsp;<span class='friend-name'>" + friend + "</span>&nbsp;&nbsp;已上线"
    sysBoCastList.appendChild(newSysBoCastItem)
}

function setTextAreaKeyEvent() {
    const textarea = document.getElementById('message');
    let sendBtn = document.getElementById("send-btn")

    textarea.addEventListener('keydown', function(event) {
        // 检查按下的键是否是回车键（keyCode为13）并且同时按下了Ctrl键
        if (event.keyCode === 13 && event.ctrlKey) {
            const cursorPosition = this.selectionStart; // 获取光标位置
            const value = this.value;
            this.value = value.substring(0, cursorPosition) + '\n' + value.substring(cursorPosition); // 插入换行符
            this.setSelectionRange(cursorPosition + 1, cursorPosition + 1); // 将光标移到新行的开头
        } else if (event.keyCode === 13) {
            event.preventDefault(); // 阻止默认的回车键行为（换行）
            sendBtn.click()
        }
    });

}